<template>
  <div class="content" v-loading="loading">
    <!--头部-->
    <div class="header-setting">
      <a-breadcrumb class="breadcrumb">
        <a-breadcrumb-item>
          <a href="../main">首页</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>收费管理</a-breadcrumb-item>
        <a-breadcrumb-item>活动充值</a-breadcrumb-item>
      </a-breadcrumb>
      <!--查询条件-->
      <div class="box-condition-body">
        <div class="box-condition-item">
          <div class="box-item">
            <div style="margin: 0 50px">订单支付时间</div>
            <template>
              <div class="button_time">
                <a-button
                  type="primary"
                  @click="button_time(0)"
                  :style="computedStyle(0)"
                  >今天</a-button
                >
                <a-button
                  type="primary"
                  @click="button_time(1)"
                  :style="computedStyle(1)"
                  >昨天</a-button
                >
                <a-button
                  type="primary"
                  @click="button_time(2)"
                  :style="computedStyle(2)"
                  >本周</a-button
                >
                <a-button
                  type="primary"
                  @click="button_time(3)"
                  :style="computedStyle(3)"
                  >上周</a-button
                >
                <a-button
                  type="primary"
                  @click="button_time(4)"
                  :style="computedStyle(4)"
                  >本月</a-button
                >
              </div>
            </template>
            <template>
              <div style="margin: auto 50px">
                <a-range-picker
                  :showTime="{ format: 'HH:mm' }"
                  format="YYYY-MM-DD HH:mm"
                  :placeholder="['开始时间', '结束时间']"
                  @ok="onOk"
                  @change="onChange"
                  :value="rangePicker()"
                />
              </div>
            </template>

              <div style="margin: 0 15px 0 50px">充值类型</div>
              <template>
                  <a-select
                          showSearch
                          placeholder="充值类型"
                          optionFilterProp="children"
                          style="width: 200px"
                          :allowClear="allowClear"
                          @select="selectActivitiesType"
                  >
                      <a-select-option
                              v-for="p in activitiesTypeOption"
                              :key="p.value"
                              :value="p.value"
                      >{{ p.label }}
                      </a-select-option>
                  </a-select>
              </template>

          </div>
        </div>
        <!--                <div class="box-condition-item">
                    <div style="margin: 0 50px">时间统计类型</div>
                    <a-button type="primary" style="margin: 0 0 0 20px" @click="timeStatistics(1)">日</a-button>
                    <a-button type="primary" style="margin: 0 0 0 20px" @click=" timeStatistics(2)">月</a-button>

                </div>-->
      </div>
    </div>

    <div class="box-form">
      <!--工具栏-->
      <div class="box-tool">
        <div>单位：元</div>
        <div style="display: flex">
          <a-button type="primary" @click="downloadDataClick" icon="download"
            >导出</a-button
          >
        </div>
      </div>
      <!--数据表格-->
      <div class="box-table">
        <a-table
          :columns="columns"
          :dataSource="dataSource"
          :pagination="pagination"
          bordered
          size="small"
          :scroll="scroll"
          :customRow="customRow"
          :rowClassName="setRowClassName"
          @change="tableChange"
        >
          <template slot="amount" slot-scope="text">
            <div>{{ text == undefined || text == "" ? text : text / 100 }}</div>
          </template>
          <template slot="amountReality" slot-scope="text">
            <div>{{ text == undefined || text == "" ? text : text / 100 }}</div>
          </template>
          <template slot="sumFavorableAmount" slot-scope="text">
            <div>{{ text == undefined || text == "" ? text : text / 100 }}</div>
          </template>
          <template slot="amountShouldButNot" slot-scope="text">
            <div>{{ text == undefined || text == "" ? text : text / 100 }}</div>
          </template>
          <template slot="pdfUrl" slot-scope="text">
            <div v-if="text != '' && text != undefined">
              <a :href="text" target="_Blank">发票预览</a>
            </div>
          </template>
           <template slot="operation1" slot-scope="text,data">
              <a v-on:click="refundWindows(data)">退款</a>
          </template>
          <!-- 脚步 -->
          <template slot="footer" v-if="dataSource.length != 0">
            <div style="display: flex; height: 30px; margin: 0 -16px">
              <div style="flex: 1 1 65%; height: 100%; padding-left: 1%">
                合计
              </div>
              <div style="flex: 1 0 20.7%; height: 100%; padding-left: 0.3%">
                {{ computedAmount }}
              </div>
            </div>
          </template>
        </a-table>
      </div>
    </div>
    <!-- 退款弹窗 -->
    <a-modal
    title="退款"
    v-model="refundPopupData.visible"
    :confirmLoading="refundPopupData.loading"
    @cancel="() => {this.hideRefundPopupData();}"
    @ok="refund">
    <div style="text-align:center">
         <font size="3" color="red">活动退款后客户账户余额为0，请谨慎退款!</font>
    </div>
   
    <a-row style="margin-top: 0.5em">
      <a-col :span="6">订单金额</a-col>
      <a-col :span="15">
        <a-input disabled v-model="refundPopupData.amount" type="text,data" />
      </a-col>
    </a-row>
    <a-row style="margin-top: 0.5em">
      <a-col :span="6">退款金额</a-col>
      <a-col :span="15">
        <a-input
          placeholder="退款金额(元)"
          defaultValue="2"
          v-model="refundPopupData.money"
          type="text"
          onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
        />
      </a-col>
    </a-row>
    <span>
      <a-row style="margin-top: 0.5em">
        <a-col :span="6">退款备注</a-col>
        <a-col :span="15">
          <a-textarea
            maxlength="100"
            placeholder="退款备注"
            v-model="refundPopupData.remark"
          />
        </a-col>
      </a-row>
    </span>
  </a-modal>
  </div>
</template>

<script>
import moment from "moment";
import CommonApi from "../../api/CommonApi";
import ActivitiesRechargeApi from "../../api/charge/ActivitiesRecharge";
import ParkingRecordApi from "../../api/charge/ChargeDetail";
const columns = [
  {
    title: "序号",
    dataIndex: "no",
    width: "5%",
  },
  {
    title: "活动名称",
    dataIndex: "activitiesName",
    width: "10%",
  },
  {
    title: "活动规则名称",
    dataIndex: "ruleName",
    width: "10%",
  },
  {
    title: "本地订单号",
    dataIndex: "outTradeNo",
    width: "10%",
  },
  {
    title: "商户订单号",
    dataIndex: "transactionOrderNo",
    width: "10%",
  },
  {
    title: "支付金额",
    dataIndex: "amount",
    scopedSlots: { customRender: "amount" },
    width: "5%",
  },
  {
    title: "订单支付时间",
    dataIndex: "orderTime",
    width: "10%",
  },
  {
    title: "发票",
    dataIndex: "pdfUrl",
    scopedSlots: { customRender: "pdfUrl" },
    width: "7%",
  },
  {
    title: "操作",
    scopedSlots: { customRender: "operation1" },
    width: "7%",
  },
];

const dataSource = [];

const queryCondition = {
  timeType: "",
  parkId: "",
  rechargeType: "",
  startTimeStamp: "",
  endTimeStamp: "",
  timeScreenCondition: 6,
  limit: "10",
  curr: "1",
};

export default {
  name: "ActivitiesRecharge",

  /*数据层*/
  data() {
    return {
      parks: [],
      selectId: -1,
      momentArr: [],
      columns: columns,
      dataSource: dataSource,
      /*分页插件*/
      pagination: {
        showTotal: (total) => `共${total}条`,
        total: 0,
        current: 1,
        defaultCurrent: 1,
        showQuickJumper: true,
        defaultPageSize: 10,
      },
      /*表格固定头部*/
      scroll: {
        y: 550,
      },
      tableState: {
        rowId: -1,
      },
      /* 订单退款 */
      refundPopupData: {
        visible: false,
        loading: false,
        wid: "",
        money: "",
        type: "",
        remark: "",
        payType: "",
        amount:"",
        orderTime:""
      },
      /*当前选中的行数据*/
      currRowData: "",
      selectParkId: "",
      timeStatisticsType: "1",
      queryCondition,
      loading: false,
      allowClear: true,
      searchType: "",
      activitiesTypeOption: [
          { value: 0, label: "全部" },
          { value: 1, label: "正常充值类" },
          { value: 2, label: "用户组活动充值" },
      ],
    };
  },

  /*方法层*/
  methods: {
    /*时间按钮控制*/
    button_time(e) {
      this.selectId = e;
      let momentStart;
      let momentEnd;
      switch (e) {
        case 0:
          momentStart = moment().startOf("day");
          momentEnd = moment().endOf("day");
          break;
        case 1:
          momentStart = moment().add("day", -1).startOf("day");
          momentEnd = moment().add("day", -1).endOf("day");
          break;
        case 2:
          momentStart = moment().week(moment().week()).startOf("week");
          momentEnd = moment().week(moment().week()).endOf("week");
          break;

        case 3:
          momentStart = moment()
            .week(moment().week() - 1)
            .startOf("week");
          momentEnd = moment()
            .week(moment().week() - 1)
            .endOf("week");
          break;
        case 4:
          momentStart = moment().month(moment().month()).startOf("month");
          momentEnd = moment().month(moment().month()).endOf("month");
          break;
        default:
          break;
      }
      this.momentArr[0] = momentStart;
      this.momentArr[1] = momentEnd;
      this.queryData();
    },
    /*日期选择*/
    onChange(date) {
      this.selectId = -1;
      this.momentArr = date;
    },
    onOk() {
      this.selectId = -1;
      this.queryData();
    },
    rangePicker() {
      return this.momentArr;
    },
    hideRefundPopupData() {
      this.refundPopupData.visible = false;
      this.refundPopupData.wid = "";
      this.refundPopupData.money = "";
      this.refundPopupData.remark = "";
      this.refundPopupData.payType = "";
      this.refundPopupData.amount = "";
      this.refundPopupData.orderTime="";
    },
    refundWindows(data){
      this.refundPopupData.visible = true;
      this.refundPopupData.loading = false;
      this.refundPopupData.wid = data.id;
      this.refundPopupData.payType = data.payType;
      this.refundPopupData.amount = data.amount/100;
      this.refundPopupData.orderTime=data.orderTime;
    },
    refund(){
      this.refundPopupData;
       if (this.refundPopupData.wid == null || this.refundPopupData.wid == "" || this.refundPopupData.wid == undefined) {
        this.$message.warn("wid参数不能为空！");
        return;
      }
      if (
        this.refundPopupData.money == null ||
        this.refundPopupData.money == "" ||
        this.refundPopupData.money == undefined ||
        this.refundPopupData.money == "0" ||
        this.refundPopupData.money == 0
      ) {
        this.$message.warn("退款金额不为为0或空！");
        return;
      }
      if (this.refundPopupData.money > this.refundPopupData.amount) {
        this.$message.warn("退款金额不能超过订单金额！");
        return;
      }
      let type = 2;
      if (
        new Date().getFullYear() == new Date(this.orderTime).getFullYear() &&
        new Date().getMonth() == new Date(this.orderTime).getMonth() &&
        new Date().getDay() == new Date(this.orderTime).getDay()
      ){
        type = 1;
      }
       //0:订单 1:活动 2:包月
      this.refundPopupData.sourceType=1;
      this.refundPopupData.type=type;
      this.refundPopupData.money=this.refundPopupData.money * 100
      ParkingRecordApi.channelRefund(this.refundPopupData)
        .then((data) => {
          let code = data.code;
          if (code === 2000) {
            this.$message.success("操作成功！");
            this.hideRefundPopupData();
            this.queryData();
          } else {
            this.$message.error("操作失败！" + data.data);
          }
        })
        .catch((error) => {
          this.$message.error("操作失败！" + error.data);
        });
      console.log(this.refundPopupData)
    },
    /*下拉框*/
    initParkList() {
      CommonApi.getParkList()
        .then((data) => {
          this.parks = data.data;
        })
        .catch((err) => {
          console.log("error:", err);
        });
    },
    selectPark(value) {
      this.selectParkId = value;
      this.queryData();
    },
    selectChanged(value) {
      if (value == undefined) {
        this.selectParkId = "";
        this.queryData();
      }
    },
    timeStatistics(type) {
      this.timeStatisticsType = "1";
      if (type != undefined) {
        this.timeStatisticsType = type;
      }
      this.queryData();
    },
    tableChange(page) {
      this.queryCondition.curr = page.current;
      this.queryData();
    },
    selectActivitiesType(value) {
        this.searchType = value;
        this.queryData();
    },
    queryData() {
      this.loading = true;
      let condition = this.getQueryCondition();
      ActivitiesRechargeApi.rechargeList(condition)
        .then((data) => {
          let { list, total, pageNum, pageSize } = data.data;
          let array = list || [];
          array = array.map((item, index) => {
            return { ...item, no: total - (pageNum - 1) * pageSize - index };
          });
          this.dataSource = array;
          this.pagination.total = total;
          this.pagination.current = pageNum;
          this.loading = false;
        })
        .catch((error) => {
          console.log("获取数据异常！", error);
          this.loading = false;
        });
    },
    getQueryCondition() {
      let condition = this.queryCondition;
      let beginMoment = this.momentArr[0];
      let endMoment = this.momentArr[1];
      condition.rechargeType = this.searchType;
      if (beginMoment != undefined && endMoment != undefined) {
        condition.startTimeStamp = new Date(beginMoment).getTime() / 1000;
        condition.endTimeStamp = new Date(endMoment).getTime() / 1000;
        condition.timeScreenCondition = 6;
      } else {
        condition.timeScreenCondition = 0;
      }
      condition.parkId = this.selectParkId;
      condition.timeType = this.timeStatisticsType;
      return condition;
    },

    downloadDataClick() {
      let condition = this.getQueryCondition();
      ActivitiesRechargeApi.exportRechargeExcel(condition)
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });
          let fileName = decodeURIComponent(res.headers.filename);
          if (fileName == null || fileName == "undefined") {
            fileName = "活动充值明细表.xlsx";
          }
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", `${fileName}`);
          link.click();
        })
        .catch((err) => {
          let data = err.data;
          if (data) {
            return this.$message.warn(data);
          }
        });
    },

    /*表格*/
    customRow(record, index) {
      return {
        on: {
          // 事件
          click: () => {
            this.currRowData = record;
            this.tableState.rowId = index;
          }, // 点击行
        },
      };
    },
    setRowClassName(record, index) {
      return index === this.tableState.rowId ? "clickRowStyl" : "";
    },
  },

  /*计算层*/
  computed: {
    computedStyle() {
      return function (selectId) {
        return this.selectId == selectId ? "" : "";
      };
    },

    computedAmount() {
      let dataSource = this.dataSource || [];
      let result = 0;
      dataSource.forEach((item) => {
        result += item.amount;
      });
      return result / 100;
    },
  },

  /*渲染层*/
  mounted() {
    this.initParkList();
    // this.queryData();
    this.button_time(0);
  },
};
</script>

<style>
.content {
  width: 100%;
  height: 100%;
}

.header-setting {
  width: 100%;
  /* height: 174px; */
  background: #fff;
}

.header-setting .breadcrumb {
  margin-left: 41px;
  padding-top: 15px;
}

/*表格行选中背景颜色*/
.clickRowStyl {
  background-color: #c1e0fd;
}

.box-condition-item {
  display: flex;
  align-items: center;
  min-width: 1500px;
  padding: 15px 0;
}

.box-condition-item .box-item {
  display: flex;
  align-items: center;
  justify-content: center;
  /*margin: 5px 5px 5px 5px;*/
}

.button_time button {
  margin-left: 10px;
}

/* 表单 */
.box-form {
  padding-left: 40px;
  padding-right: 40px;
  min-height: 705px;
  background: #fff;
  margin-top: 8px;
}

.box-form .box-tool {
  padding-top: 11px;
  margin: 8px 0;
  width: 100%;
  /* flex */
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
